<!-- templates/accounts/register.html -->
{% extends 'base.html' %}

{% block title %}注册 - AI故事生成器{% endblock %}

{% block content %}
<div class="auth-container">
    <h1>用户注册</h1>
    <div id="register-message" class="message"></div>
    <form id="registerForm" class="auth-form" onsubmit="return handleRegister(event)">
        {% csrf_token %}
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" placeholder="请输入用户名（选填）">
        </div>
        
        <div class="form-group">
            <label for="email">邮箱</label>
            <input type="email" id="email" name="email" placeholder="请输入邮箱（选填）">
            <small>用户名和邮箱至少填写一个</small>
        </div>
        
        <div class="form-group">
            <label for="nickname">昵称</label>
            <input type="text" id="nickname" name="nickname" placeholder="请输入昵称（选填）" maxlength="11">
        </div>
        
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" placeholder="请输入密码" required>
        </div>
        
        <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input type="password" id="confirmPassword" name="confirmPassword" placeholder="请再次输入密码" required>
        </div>
        
        <button type="submit" class="btn">注册</button>
    </form>
    
    <p class="auth-switch">
        已有账户？<a href="{% url 'user:login' %}">立即登录</a>
    </p>
</div>

<script>
// 防止重复提交的标志
let isSubmitting = false;

function handleRegister(event) {
    event.preventDefault();
    
    // 防止重复提交
    if (isSubmitting) {
        console.log('正在提交中，请勿重复点击');
        return false;
    }
    
    console.log('注册表单提交');
    
    const messageEl = document.getElementById('register-message');
    const username = document.getElementById('username').value.trim();
    const email = document.getElementById('email').value.trim();
    const nickname = document.getElementById('nickname').value.trim();
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    
    // 前端验证 - 用户名和邮箱至少填写一个
    if ((!username && !email) || !password || !confirmPassword) {
        showMessage(messageEl, '用户名和邮箱至少填写一个，密码必填', 'error');
        return false;
    }
    
    if (password !== confirmPassword) {
        showMessage(messageEl, '密码和确认密码不匹配', 'error');
        return false;
    }
    
    if (password.length < 1) {
        showMessage(messageEl, '密码不能为空', 'error');
        return false;
    }
    
    // 设置提交状态
    isSubmitting = true;
    
    // 显示加载状态
    const submitButton = document.querySelector('#registerForm button[type="submit"]');
    const originalText = submitButton.textContent;
    submitButton.textContent = '注册中...';
    submitButton.disabled = true;
    
    // 隐藏之前的消息
    messageEl.style.display = 'none';
    
    // 收集表单数据
    const formData = new FormData(document.getElementById('registerForm'));
    
    // 发送注册请求
    fetch('/user/register/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': getCSRFToken()
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络请求失败');
        }
        return response.json();
    })
    .then(data => {
        console.log('注册响应:', data);
        if (data.success) {
            showMessage(messageEl, data.message, 'success');
            // 清空表单
            document.getElementById('registerForm').reset();
            // 延迟跳转，让用户看到成功消息
            setTimeout(() => {
                window.location.href = '/user/login/';
            }, 1500);
        } else {
            showMessage(messageEl, data.message, 'error');
        }
    })
    .catch(error => {
        console.error('注册错误:', error);
        showMessage(messageEl, '注册过程中发生网络错误，请检查网络连接后重试', 'error');
    })
    .finally(() => {
        // 恢复按钮状态和提交标志
        isSubmitting = false;
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
    
    return false;
}

function showMessage(element, message, type) {
    element.textContent = message;
    element.className = 'message ' + type;
    element.style.display = 'block';
    
    // 错误消息5秒后自动隐藏，成功消息3秒后隐藏
    const hideDelay = type === 'error' ? 5000 : 3000;
    setTimeout(() => {
        if (element.style.display === 'block') {
            element.style.display = 'none';
        }
    }, hideDelay);
}

function getCSRFToken() {
    // 从表单中获取CSRF token
    const csrfInput = document.querySelector('input[name="csrfmiddlewaretoken"]');
    if (csrfInput) {
        return csrfInput.value;
    }
    // 从 cookie中获取
    return getCookie('csrftoken');
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>
{% endblock %}